package com.ilxqx.framework.security.filter;

import com.ilxqx.framework.security.util.AuthUtils;
import com.ilxqx.framework.security.util.KeyUtils;
import com.ilxqx.framework.system.util.ResponseUtils;
import com.ilxqx.framework.util.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author venus
 */
public class AccessKeyFilter extends OncePerRequestFilter {

    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param filterChain 过滤器链
     */
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (!AuthUtils.authenticationTrustResolver.isAnonymous(authentication) && authentication.isAuthenticated()) {
            // 检测用户key是否合法
            String key = request.getHeader("X-Access-Key");
            boolean keyInvalid = StringUtils.isEmpty(key) || !KeyUtils.match(request.getRemoteAddr(), request.getHeader(HttpHeaders.USER_AGENT), key);
            if (keyInvalid) {
                // 验证失败，重新登录
                /// 是否立即清除验证信息
                // SecurityUtils.logout(request);
                logger.info("AccessKey验证失败，请重新登录");
                ResponseUtils.response(ResultUtils.invalidKey("AccessKey无效，请重新登录"), request, response);
                return;
            }
        }

        // 验证成功或者不需要验证
        filterChain.doFilter(request, response);
    }

}
